<template>
  <div class="account-settings-info-view">
    <a-row :gutter="16">
      <a-col :md="24" :lg="16">

        <a-form ref="formEditUserInfo" :form="form" id="formEditUserInfo" layout="vertical">
          <a-form-item
            label="昵称"
          >
            <a-input
              placeholder="给自己起个名字"
              v-decorator="['nickname', {initialValue:nickname}, {rules: [{ required: false, message: '请输入昵称' }], validateTrigger: ['change', 'blur']}]"
            />
          </a-form-item>
          <a-form-item
            label="个人签名"
          >
            <a-textarea
              rows="4"
              placeholder="You are not alone."
              v-decorator="['sign', {initialValue:userInfo.memInfo.sign}, {rules: [{ required: false, message: '请输入个人签名' }], validateTrigger: ['change', 'blur']}]"
            />
          </a-form-item>
          <a-form-item
            label="会员性别"
          >
            <a-select
              v-decorator="['sex',{initialValue:(userInfo.memInfo.sex?'1':'0')} ,{rules:[{required: false, message: '请选择会员性别'}]}]">
              <a-select-option value="1">男</a-select-option>
              <a-select-option value="0">女</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item
            label="会员年龄"
          >
            <a-input
              v-decorator="['age', {initialValue:userInfo.memInfo.age}, {rules:[{required: false, message: '请输入会员年龄'}]}]" />
          </a-form-item>
          <a-form-item>
            <a-button
              class="ant-btn-primary"
              htmlType="submit"
              :loading="saveBtn"
              @click.stop.prevent="handleSubmit"
              :disabled="saveBtn">保存
            </a-button>
          </a-form-item>
        </a-form>

      </a-col>
      <a-col :md="24" :lg="8" :style="{ minHeight: '180px' }">
        <div class="ant-upload-preview" @click="$refs.modal.edit(1)">
          <a-icon type="cloud-upload-o" class="upload-icon" />
          <div class="mask">
            <a-icon type="plus" />
          </div>
          <img :src="option.img||avatar" />
        </div>
      </a-col>

    </a-row>

    <avatar-modal ref="modal" @ok="setavatar" />

  </div>
</template>

<script>
import { getSmsCaptcha } from '@/api/login'
import AvatarModal from './AvatarModal'
import aclApi from '@/api/acl'
import { mapGetters } from 'vuex'
// import md5 from 'md5'

const levelNames = {
  0: '低',
  1: '低',
  2: '中',
  3: '强'
}
const levelClass = {
  0: 'error',
  1: 'error',
  2: 'warning',
  3: 'success'
}
const levelColor = {
  0: '#ff0000',
  1: '#ff0000',
  2: '#ff7e05',
  3: '#52c41a'
}

export default {
  components: {
    AvatarModal
  },
  data () {
    return {
      // cropper
      preview: {},
      form: this.$form.createForm(this),

      state: {
        time: 60,
        smsSendBtn: false,
        passwordLevel: 0,
        passwordLevelChecked: false,
        percent: 10,
        progressColor: '#FF0000'
      },
      saveBtn: false,
      option: {
        img: '',
        info: true,
        size: 1,
        outputType: 'jpeg',
        canScale: false,
        autoCrop: true,
        // 只有自动截图开启 宽度高度才生效
        autoCropWidth: 180,
        autoCropHeight: 180,
        fixedBox: true,
        // 开启宽度和高度比例
        fixed: true,
        fixedNumber: [1, 1]
      }
    }
  },
  computed: {
    ...mapGetters(['nickname', 'username', 'avatar', 'userInfo']),
    passwordLevelClass () {
      return levelClass[this.state.passwordLevel]
    },
    passwordLevelName () {
      return levelNames[this.state.passwordLevel]
    },
    passwordLevelColor () {
      return levelColor[this.state.passwordLevel]
    }
  },
  methods: {
    setavatar (url) {
      console.log(url)
      this.option.img = url
    },
    handlePasswordLevel (rule, value, callback) {
      let level = 0

      // 判断这个字符串中有没有数字
      if (/[0-9]/.test(value)) {
        level++
      }
      // 判断字符串中有没有字母
      if (/[a-zA-Z]/.test(value)) {
        level++
      }
      // 判断字符串中有没有特殊符号
      if (/[^0-9a-zA-Z_]/.test(value)) {
        level++
      }
      this.state.passwordLevel = level
      this.state.percent = level * 30
      if (level >= 2) {
        if (level >= 3) {
          this.state.percent = 100
        }
        callback()
      } else {
        if (level === 0) {
          this.state.percent = 10
        }
        callback(new Error('密码强度不够'))
      }
    },

    handlePasswordCheck (rule, value, callback) {
      const password = this.form.getFieldValue('password')
      console.log('value', value)
      if (value === undefined) {
        callback(new Error('请输入密码'))
      }
      if (value && password && value.trim() !== password.trim()) {
        callback(new Error('两次密码不一致'))
      }
      callback()
    },

    handlePhoneCheck (rule, value, callback) {
      console.log('handlePhoneCheck, rule:', rule)
      console.log('handlePhoneCheck, value', value)
      console.log('handlePhoneCheck, callback', callback)

      callback()
    },

    handlePasswordInputClick () {
      if (!this.isMobile) {
        this.state.passwordLevelChecked = true
        return
      }
      this.state.passwordLevelChecked = false
    },

    handleSubmit () {
      const { form: { validateFields }, state, $notification } = this
      validateFields({ force: true }, (err, values) => {
        if (!err) {
          state.passwordLevelChecked = false
          values.sex = values.sex === '1'
          values.userId = this.userInfo.memInfo.userId
          values.avatar = this.option.img || this.avatar
          console.log(values.userId)
          aclApi.editUserInfo(values).then(res => {
            if (res.code === 20000) {
              $notification['success']({
                message: '提示',
                description: res.message,
                duration: 8
              })
            } else {
              $notification['error']({
                message: '提示',
                description: res.message,
                duration: 8
              })
            }
          })
        }
      })
    },

    getCaptcha (e) {
      e.preventDefault()
      const { form: { validateFields }, state, $message, $notification } = this

      validateFields(['mobile'], { force: true },
        (err, values) => {
          if (!err) {
            state.smsSendBtn = true

            const interval = window.setInterval(() => {
              if (state.time-- <= 0) {
                state.time = 60
                state.smsSendBtn = false
                window.clearInterval(interval)
              }
            }, 1000)

            const hide = $message.loading('验证码发送中..', 0)

            getSmsCaptcha({ mobile: values.mobile }).then(res => {
              if (res.code === 200) {
                setTimeout(hide, 1000)
                $notification['success']({
                  message: '提示',
                  description: '验证码发送成功!',
                  duration: 8
                })
              }
            }).catch(err => {
              setTimeout(hide, 1)
              clearInterval(interval)
              state.time = 60
              state.smsSendBtn = false
              this.requestFailed(err)
            })
          }
        }
      )
    },
    requestFailed (err) {
      this.$notification['error']({
        message: '错误',
        description: ((err.response || {}).data || {}).message || '请求出现错误，请稍后再试',
        duration: 4
      })
      this.registerBtn = false
    }
  },
  watch: {
    'state.passwordLevel' (val) {
      console.log(val)
    }
  }
}
</script>

<style lang="less" scoped>

.avatar-upload-wrapper {
  height: 200px;
  width: 100%;
}

.ant-upload-preview {
  position: relative;
  margin: 0 auto;
  width: 100%;
  max-width: 180px;
  border-radius: 50%;
  box-shadow: 0 0 4px #ccc;

  .upload-icon {
    position: absolute;
    top: 0;
    right: 10px;
    font-size: 1.4rem;
    padding: 0.5rem;
    background: rgba(222, 221, 221, 0.7);
    border-radius: 50%;
    border: 1px solid rgba(0, 0, 0, 0.2);
  }

  .mask {
    opacity: 0;
    position: absolute;
    background: rgba(0, 0, 0, 0.4);
    cursor: pointer;
    transition: opacity 0.4s;

    &:hover {
      opacity: 1;
    }

    i {
      font-size: 2rem;
      position: absolute;
      top: 50%;
      left: 50%;
      margin-left: -1rem;
      margin-top: -1rem;
      color: #d6d6d6;
    }
  }

  img, .mask {
    width: 100%;
    max-width: 180px;
    height: 100%;
    border-radius: 50%;
    overflow: hidden;
  }
}
</style>
